public class Practice2 {
    //https://leetcode.cn/problems/H6lPxb/description/
    //并查集-相似字符串
    public int HMAX = 301;
    public int[] farther = new int[HMAX];
    public int set;
    public void build(int n){
        for(int i = 0;i < n;i++){
            farther[i] = i;
        }
        set = n;
    }

    public int find(int n){
        if(farther[n] != n){
            farther[n] = find(farther[n]);
        }
        return farther[n];
    }

    public boolean isSameSet(int a,int b){
        return find(a) == find(b);
    }

    public void union(int a,int b){
        int fa = find(a);
        int fb = find(b);
        if(fa != fb)
            farther[fa] = farther[fb];
        set--;

    }
    public int numSimilarGroups(String[] strs) {
        build(strs.length);
        for (int i = 0; i < strs.length - 1; i++) {
            for (int j = i + 1; j < strs.length; j++) {
                if (find(i) != find(j)) {
                    int diff = 0;
                    for (int k = 0; k < strs[i].length() && diff < 3; k++) {
                        if (strs[i].charAt(k) != strs[j].charAt(k)) {
                            diff += 1;
                        }
                    }
                    if (diff == 0 || diff == 2) {
                        union(i, j);
                    }
                }

            }
        }
        return set;
    }
}
